package okhttp.itydl.com.download.proxy;

import android.support.annotation.NonNull;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池创建
 * 通过构造方法，自己根据具体场景定制线程池的线程数量
 *
 * @author howard
 */
public class ThreadPoolProxy {

    public ThreadPoolExecutor sExecutor;
    private int corePoolSize;
    private int maximumPoolSize;
    private long keepAliveTime;

    public ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.keepAliveTime = keepAliveTime;
    }

    public ThreadPoolExecutor initThreadPoolExectutor() {
        if (sExecutor == null) {
            synchronized (ThreadPoolProxy.class) {
                if (sExecutor == null) {
                    TimeUnit unit = TimeUnit.MILLISECONDS;
                    BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<Runnable>();
                    ThreadFactory threadFactory = new ThreadFactory() {
                        private AtomicInteger atomicInteger = new AtomicInteger(1);
                        @Override
                        public Thread newThread(@NonNull Runnable r) {
                            Thread thread = new Thread(r,"new Thread ##"+atomicInteger.getAndIncrement());
                            return thread;
                        }
                    };
                    sExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
                            threadFactory);
                }
            }
        }
        return sExecutor;
    }

    /**
     * 线程池异步执行任务
     * @param task
     */
    public void executor(Runnable task){
        initThreadPoolExectutor();
        sExecutor.execute(task);
    }

    /**
     * 提交任务
     */
    public Future<?> submit(Runnable task) {
        initThreadPoolExectutor();
        return sExecutor.submit(task);
    }

    /**
     * 移除任务
     */
    public void removeTask(Runnable task) {
        initThreadPoolExectutor();
        sExecutor.remove(task);
    }
}
